package com.saxon.system.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

public class JwtFilter extends GenericFilter {
    @Override
    public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String token = httpServletRequest.getHeader ("token");
        DecodedJWT verify = JWT.require (Algorithm.HMAC256 ("sss")).build ().verify (token);
        String username = verify.getClaim ("username").asString ();
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList (verify.getClaim ("authorities").asString ());
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken (username, null, authorities);
        SecurityContextHolder.getContext ().setAuthentication (usernamePasswordAuthenticationToken);
        filterChain.doFilter (httpServletRequest, servletResponse);
    }
}
